<template>
  <div class="form-container">
    <el-card class="form-list">
      <template #header>
        <div class="card-header">
          <span>表单列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="handlePreviewAll">预览全部</el-button>
            <el-button type="primary" @click="handleViewGlobalJson">查看JSON</el-button>
            <el-button type="primary" @click="handleCreateForm('section')">新建章节</el-button>
            <el-button type="primary" @click="handleCreateForm('form')">新建表单</el-button>
          </div>
        </div>
      </template>
      
      <el-tree
        ref="treeRef"
        :data="formList"
        :props="{ 
          children: 'children',
          label: 'name'
        }"
        node-key="id"
        default-expand-all
        draggable
        @node-drag-end="handleDragEnd"
      >
        <template #default="{ data }">
          <div class="tree-node">
            <div class="node-content">
              <el-tag 
                :type="data.type === 'section' ? 'info' : ''"
                size="small"
                class="node-type"
              >
                {{ data.type === 'section' ? '章节' : '表单' }}
              </el-tag>
              <span class="node-label">{{ data.name }}</span>
              <span class="node-code" v-if="false"></span>
            </div>
            <div class="node-actions">
              <el-tag 
                v-if="data.type !== 'section'"
                :type="data.status === '已发布' ? 'success' : 'warning'"
                size="small"
              >
                {{ data.status }}
              </el-tag>
              <el-button-group class="action-buttons">
                <el-button 
                  link 
                  type="primary" 
                  @click.stop="handleEdit(data)"
                >
                  编辑
                </el-button>
                <el-button 
                  v-if="data.type === 'section'"
                  link 
                  type="primary" 
                  @click.stop="handleCreateForm('form', data)"
                >
                  添加表单
                </el-button>
                <el-button 
                  v-if="data.type !== 'section'"
                  link 
                  type="primary" 
                  @click.stop="handleDesign(data)"
                >
                  设计
                </el-button>
                <el-button 
                  v-if="data.type !== 'section'"
                  link 
                  type="primary" 
                  @click.stop="handlePreview(data)"
                >
                  预览
                </el-button>
                <el-button 
                  v-if="data.type !== 'section' && data.status !== '已发布'"
                  link 
                  type="success" 
                  @click.stop="handlePublish(data)"
                >
                  发布
                </el-button>
                <el-button 
                  v-if="data.type !== 'section' && data.status === '已发布'"
                  link 
                  type="warning" 
                  @click.stop="handleUnpublish(data)"
                >
                  下线
                </el-button>
                <el-button 
                  link 
                  type="danger" 
                  @click.stop="handleDelete(data)"
                >
                  删除
                </el-button>
              </el-button-group>
            </div>
          </div>
        </template>
      </el-tree>
    </el-card>

    <!-- 新建/编辑表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="getDialogTitle"
      width="50%"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" :placeholder="formData.type === 'section' ? '请输入章节名称' : '请输入表单名称'" />
        </el-form-item>
        
        <template v-if="formData.type !== 'section'">
          <el-form-item label="表单类型" prop="formType">
            <el-select v-model="formData.formType" placeholder="请选择表单类型" style="width: 100%">
              <el-option label="基础表单" value="basic" />
              <el-option label="复杂表单" value="complex" />
            </el-select>
          </el-form-item>
        </template>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :placeholder="formData.type === 'section' ? '请输入章节说明' : '请输入表单说明'"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 表单设计器对话框 -->
    <el-dialog
      v-model="designerVisible"
      title="表单设计器"
      width="90%"
      :destroy-on-close="true"
      class="designer-dialog"
    >
      <FormDesigner 
        ref="designerRef"
        :form-data="currentForm"
        @save="handleSaveDesign"
      />
    </el-dialog>

    <!-- JSON 预览对话框 -->
    <el-dialog
      v-model="jsonDialogVisible"
      title="全局配置 JSON"
      width="80%"
      class="json-dialog"
    >
      <div class="json-toolbar">
        <el-radio-group v-model="jsonViewMode" size="small">
          <el-radio-button label="structure">表单结构</el-radio-button>
          <el-radio-button label="full">完整配置</el-radio-button>
        </el-radio-group>
        <el-button
          type="primary"
          size="small"
          @click="handleCopyJson"
        >
          复制到剪贴板
        </el-button>
      </div>
      <div class="json-content">
        <pre>{{ formattedJson }}</pre>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import FormDesigner from '../components/FormDesigner.vue'

const router = useRouter()

// 示例数据结构
const formList = ref([
  {
    id: 1,
    type: 'section',
    name: '访视信息',
    children: [
      {
        id: 2,
        type: 'form',
        name: '访视日期表',
        code: 'SV',
        formType: 'basic',
        status: '已发布',
        creator: 'admin1',
        createTime: '2024-01-10 10:00',
        updateTime: '2024-01-15 14:30'
      }
    ]
  },
  {
    id: 3,
    type: 'section',
    name: '人口学信息',
    children: [
      {
        id: 4,
        type: 'form',
        name: '人口学资料',
        code: 'DM',
        formType: 'complex',
        status: '草稿',
        creator: 'admin1',
        createTime: '2024-01-12 15:20',
        updateTime: '2024-01-15 11:20'
      }
    ]
  },
  {
    id: 5,
    type: 'section',
    name: '病史记录',
    children: [
      {
        id: 6,
        type: 'form',
        name: '既往病史',
        code: 'MH',
        formType: 'complex',
        status: '已发布',
        creator: 'admin1',
        createTime: '2024-01-14 09:00',
        updateTime: '2024-01-14 16:45'
      }
    ]
  }
])

const dialogVisible = ref(false)
const dialogType = ref('create')
const formRef = ref(null)
const treeRef = ref(null)
const currentParent = ref(null)

const formData = reactive({
  type: 'form',
  name: '',
  code: '',
  formType: '',
  remark: ''
})

const rules = {
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ],
  formType: [
    { required: true, message: '请选择表单类型', trigger: 'change' }
  ]
}

const getDialogTitle = computed(() => {
  const action = dialogType.value === 'create' ? '新建' : '编辑'
  const type = formData.type === 'section' ? '章节' : '表单'
  return `${action}${type}`
})

const designerVisible = ref(false)
const designerRef = ref(null)
const currentForm = ref(null)

const handleCreateForm = (type, parent = null) => {
  dialogType.value = 'create'
  formData.type = type
  formData.name = ''
  formData.code = ''
  formData.formType = ''
  formData.remark = ''
  currentParent.value = parent
  dialogVisible.value = true
}

const handleEdit = (data) => {
  dialogType.value = 'edit'
  formData.type = data.type
  formData.name = data.name
  formData.code = ''
  formData.formType = data.formType || ''
  formData.remark = data.remark || ''
  currentParent.value = null
  dialogVisible.value = true
}

const handleDesign = (data) => {
  // 从 localStorage 获取表单配置
  let formConfig = { fields: [] }
  try {
    const savedConfig = localStorage.getItem(`form_${data.id}_config`)
    if (savedConfig) {
      formConfig = JSON.parse(savedConfig)
    }
  } catch (error) {
    console.error('Load form config error:', error)
  }

  // 设置当前表单
  currentForm.value = {
    ...data,
    config: formConfig
  }
  designerVisible.value = true
}

const handlePreview = (data) => {
  // 实现预览逻辑
  console.log('Preview form:', data)
}

const handlePublish = (data) => {
  ElMessageBox.confirm(
    '确定要发布该表单吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      data.status = '已发布'
      ElMessage.success('发布成功')
    })
    .catch(() => {})
}

const handleUnpublish = (data) => {
  ElMessageBox.confirm(
    '确定要下线该表单吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      data.status = '草稿'
      ElMessage.success('下线成功')
    })
    .catch(() => {})
}

const handleDelete = (data) => {
  ElMessageBox.confirm(
    '确定要删除吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const deleteNode = (list, id) => {
        for (let i = 0; i < list.length; i++) {
          if (list[i].id === id) {
            list.splice(i, 1)
            return true
          }
          if (list[i].children) {
            if (deleteNode(list[i].children, id)) {
              return true
            }
          }
        }
        return false
      }
      
      deleteNode(formList.value, data.id)
      ElMessage.success('删除成功')
    })
    .catch(() => {})
}

const handleDragEnd = (draggingNode, dropNode, dropType, ev) => {
  // 实现拖拽排序逻辑
  console.log('Drag end:', { draggingNode, dropNode, dropType })
}

const handleSubmitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    if (dialogType.value === 'create') {
      const newNode = {
        id: Date.now(),
        type: formData.type,
        name: formData.name,
        remark: formData.remark
      }
      
      if (formData.type === 'form') {
        Object.assign(newNode, {
          
          formType: formData.formType,
          status: '草稿',
          creator: 'admin1',
          createTime: new Date().toLocaleString(),
          updateTime: new Date().toLocaleString()
        })
      } else {
        newNode.children = []
      }
      
      if (currentParent.value) {
        currentParent.value.children.push(newNode)
      } else {
        formList.value.push(newNode)
      }
    } else {
      // 更新节点
      const updateNode = (list, name) => {
        for (const node of list) {
          if (node.name === name) {
            Object.assign(node, {
              name: formData.name,
              remark: formData.remark,
              ...(node.type === 'form' ? {
                
                formType: formData.formType,
                updateTime: new Date().toLocaleString()
              } : {})
            })
            return true
          }
          if (node.children && updateNode(node.children, name)) {
            return true
          }
        }
        return false
      }
      
      updateNode(formList.value, formData.name)
    }
    
    dialogVisible.value = false
    ElMessage.success(`${dialogType.value === 'create' ? '创建' : '更新'}成功`)
  } catch (error) {
    console.error('Form validation error:', error)
  }
}

const handleSaveDesign = (formData) => {
  try {
    // 1. 保存到 localStorage
    localStorage.setItem(`form_${currentForm.value.id}_config`, JSON.stringify(formData))
    
    // 2. 更新表单的时间戳
    const updateFormTimestamp = (list, formId) => {
      for (const item of list) {
        if (item.type === 'section' && item.children) {
          for (const form of item.children) {
            if (form.id === formId) {
              form.updateTime = new Date().toLocaleString()
              return true
            }
          }
        }
      }
      return false
    }

    // 3. 更新时间戳并保存表单列表
    if (updateFormTimestamp(formList.value, currentForm.value.id)) {
      localStorage.setItem('formList', JSON.stringify(formList.value))
      ElMessage.success('保存成功')
      designerVisible.value = false
    } else {
      throw new Error('未找到对应的表单')
    }
  } catch (error) {
    console.error('Save design error:', error)
    ElMessage.error('保存失败')
  }
}

// 预览全部表单
const handlePreviewAll = () => {
  // 保存当前表单列表到 localStorage
  try {
    localStorage.setItem('formList', JSON.stringify(formList.value))
    
    // 保存每个表单的配置
    formList.value.forEach(section => {
      if (section.type === 'section' && section.children) {
        section.children.forEach(form => {
          if (form.type === 'form' && form.config) {
            localStorage.setItem(`form_${form.id}_config`, JSON.stringify(form.config))
          }
        })
      }
    })
    
    // 跳转到预览页面
    router.push('/preview')
  } catch (error) {
    console.error('Save form data error:', error)
    ElMessage.error('保存表单数据失败')
  }
}

// JSON 预览相关
const jsonDialogVisible = ref(false)
const jsonViewMode = ref('structure')
const formattedJson = computed(() => {
  const data = jsonViewMode.value === 'structure' 
    ? formList.value 
    : generateFullConfig()
  return JSON.stringify(data, null, 2)
})

// 生成完整配置
const generateFullConfig = () => {
  const config = {
    sections: formList.value.map(section => {
      if (section.type !== 'section') return null
      
      return {
        id: section.id,
        name: section.name,
        type: section.type,
        forms: section.children.map(form => {
          if (form.type !== 'form') return null
          
          // 尝试从 localStorage 获取表单配置
          let formConfig = form.config || {}
          try {
            const savedConfig = localStorage.getItem(`form_${form.id}_config`)
            if (savedConfig) {
              formConfig = JSON.parse(savedConfig)
            }
          } catch (error) {
            console.error(`Load form ${form.id} config error:`, error)
          }
          
          return {
            id: form.id,
            name: form.name,
            
            type: form.type,
            formType: form.formType,
            status: form.status,
            config: formConfig,
            createTime: form.createTime,
            updateTime: form.updateTime,
            creator: form.creator
          }
        }).filter(Boolean)
      }
    }).filter(Boolean)
  }
  
  return config
}

// 查看全局 JSON
const handleViewGlobalJson = () => {
  jsonDialogVisible.value = true
}

// 复制 JSON 到剪贴板
const handleCopyJson = async () => {
  try {
    await navigator.clipboard.writeText(formattedJson.value)
    ElMessage.success('已复制到剪贴板')
  } catch (error) {
    console.error('Copy error:', error)
    ElMessage.error('复制失败')
  }
}
</script>

<style lang="scss" scoped>
.form-container {
  .form-list {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
  }
  
  .tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 8px;
    
    .node-content {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .node-type {
        min-width: 40px;
        text-align: center;
      }
      
      .node-label {
        font-weight: bold;
      }
      
      .node-code {
        color: #666;
        font-size: 12px;
      }
    }
    
    .node-actions {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .action-buttons {
        margin-left: 8px;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-tree-node__content) {
  height: auto;
  padding: 8px 0;
}

.designer-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
    height: calc(90vh - 120px);
    overflow: auto;
  }
}

.json-dialog {
  .json-toolbar {
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #e4e7ed;
  }
  
  .json-content {
    padding: 16px;
    max-height: calc(90vh - 200px);
    overflow: auto;
    
    pre {
      margin: 0;
      white-space: pre-wrap;
      word-wrap: break-word;
      font-family: monospace;
      font-size: 14px;
      background-color: #f5f7fa;
      padding: 16px;
      border-radius: 4px;
    }
  }
}
</style> 